#include <stdlib.h>
#include <stdio.h>
#include "list.h"

List *create() {
    List *list = (List *) malloc(sizeof(List));
    list->header = NULL;
    list->tail = NULL;
    list->length = length;
    list->add = add;
    list->clear = clear;
    list->get = get;
    list->size = 0;
    return list;
}

int add(List *list, int num) {
    if (list != NULL) {
        Node *newNode = (Node *) malloc(sizeof(Node));
        newNode->num = num;
        newNode->next = NULL;
        if (list->header == NULL) {
            list->header = newNode;
            list->tail = newNode;
            newNode->prev = NULL;
            list->size = 1;
        } else {
            Node *temp = list->tail;
            newNode->prev = temp;
            temp->next = newNode;
            list->tail = newNode;
            list->size++;
        }
        return 1;
    }
    return 0;
}

void clear(List *list) {
    if (list != NULL) {
        Node *node = list->header;
        Node *temp = node;
        while (node != NULL) {
            temp = node->next;
            free(node);
            node = temp;
        }
        node = NULL;
        temp = NULL;
        free(list);
        list = NULL;
    }
}

int length(List *list) {
    if (list != NULL) {
        return list->size;
    }
    return -1;
}

Node *get(List *list, int index) {
    if (list != NULL) {
        if (index < list->size && index >= 0) {
            Node *temp;
            /**
             * 下标在链表右侧，从尾指针开始查找
             */
            if (index > (list->size / 2)) {
                temp = list->tail;
                for (int i = 0; i < list->size - index - 1; ++i) {
                    temp = temp->prev;
                }
            } else {
                /**
                 * 下标在链表左侧，从头指针开始查找
                 */
                temp = list->header;
                for (int i = 0; i < index; i++) {
                    temp = temp->next;
                }
            }
            return temp;
        }
    }
    return NULL;
}

void printList(List *list) {
    if (list != NULL && list->size != 0) {
        printf("list:");
        for (int i = 0; i < list->length(list) - 1; ++i) {
            printf("%d -> ", list->get(list, i)->num);
        }
        printf("%d\n", list->get(list, list->size - 1)->num);
    } else {
        printf("empty list\n");
    }
}